﻿using LdtCommonFreeSql;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ManageModel.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Net.Mime.MediaTypeNames;
using LdtCommonUtil;
using System.Dynamic;
using System.Threading.Tasks;
using System.Formats.Asn1;
using System.Globalization;
using CsvHelper;
using Newtonsoft.Json.Linq;
using System.Data.SqlTypes;
using System.Xml;
using static FreeSql.Internal.GlobalFilter;
using CommConfig;

namespace ManageModel.Bll
{
    public class ServiceBll
    {
        private readonly ILogger<ServiceBll> logger;
        private readonly FreesqlDb freesqlDb;
        private readonly IFreeSql freeSqlCaseCreate52;
        public ServiceBll(ILogger<ServiceBll> logger, FreesqlDb freesqlDb)
        {
            this.logger = logger;
            this.freesqlDb = freesqlDb;
            freeSqlCaseCreate52 = freesqlDb.GetFreeSql("casecausecreate", new ConnConfig
            {
                Dbcode = "casecausecreate",
                Dbtype = FreeSql.DataType.PostgreSQL,
                IP = "192.168.1.52",
                MaxPool = "1",
                Password = "ldtlaw@123",
                Port = "5432",
                Username = "ldt"
            });
        }
        /// <summary>
        /// Gets the train datas.
        /// </summary>
        /// <returns></returns>
        public async Task GetTrainDatas()
        {
            Random random = new Random();
            List<BgeModel> trains = new List<BgeModel>();
            List<string> modelTables = new List<string> { "dqqingxing" };
            foreach (var tableName in modelTables)
            {
                var sql1 = $"select DISTINCT regexp_split_to_table (type,',') as signcode FROM {tableName} where istrain=1";
                var temp1 = await freeSqlCaseCreate52.Ado.CommandFluent(sql1).CommandTimeout(360).QueryAsync<dynamic>();
                var category = temp1.Select(p => $"{p["signcode"]}".Split("_")[1]).OrderBy(p => p).ToList();

                var sql = $"SELECT id ,content ,type from {tableName} where istrain=1 and type is not null and type!=''";
                var trainAlls = freeSqlCaseCreate52.Ado.CommandFluent(sql).CommandTimeout(360).Query<dynamic>().ToList();
                var r1 = trainAlls.Select(p =>
                {
                    var ttyp1 = $"{p["type"]}";
                    var types = ttyp1.Split(",", System.StringSplitOptions.RemoveEmptyEntries).Select(a => a.Split("_")[1]);
                    var rrr1 = new BgeModel
                    {
                        query = $"{p["content"]}",
                        pos = types.ToList(),
                        neg = category.Where(a => !types.Contains(a)).OrderBy(aa => random.Next()).ToList()
                    };
                    //可以一个正样本对应所有负样本
                    return rrr1;
                }).OrderBy(b => random.Next()).ToList();
                trains.AddRange(r1);
            }
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
            jsonSerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
            File.WriteAllLines(Path.Combine(AppContext.BaseDirectory, "train.json"), trains.Select(p => JsonConvert.SerializeObject(p, jsonSerializerSettings)));
        }
    }
    public sealed class MyExtendsObject : DynamicObject
    {
        private readonly Dictionary<string, object> _properties;

        public MyExtendsObject(Dictionary<string, object> properties)
        {
            _properties = properties;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return _properties.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                result = _properties[binder.Name];
                return true;
            }
            else
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                _properties[binder.Name] = value;
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
